#       {
#             "parentExtKey": "-1",
#             "regionExtKey": "446623465822814208",
#             "regionCode": "test-r-01",
#             "regionName": "测是区域01",
#             "remarks": null,
#             "isDeleted": true,
#             "isUsed": true,
#             "deleteTime": "2023-03-28 13:28:09.0",
#             "modifyTime": "2023-03-28 13:27:09.0",
#             "sysModifyTime": "2023-03-28 14:02:24.773"
#         }
from module.huada.entity.base_entity import BaseEntity
from plugin import MSsqlClient, Config, Mylogger, MyTime


class AreaEntity(BaseEntity):
    url = "tunion/get/area"
    table_name = "area"
    api_data_list = []
    create_table = True
    get_time = "2000-01-01 00:00:00"
    order_by = "sysModifyTime"
    sync_list = []
    write_back_dict = {}
    update_cache_time = '2021-01-01 00:00:00'

    def __init__(self, **kwargs) -> None:
        self.parentExtKey = kwargs.get('parentExtKey')  # 父级主键
        self.regionExtKey = kwargs.get('regionExtKey')  # 区域主键
        self.regionCode = kwargs.get('regionCode')  # 区域编码
        self.regionName = kwargs.get('regionName')  # 区域名称
        self.remarks = kwargs.get('remarks')  # 备注
        self.isDeleted = kwargs.get('isDeleted')  # 是否删除
        self.isUsed = kwargs.get('isUsed')  # 是否启用
        self.deleteTime = kwargs.get('deleteTime')  # 删除时间
        self.modifyTime = kwargs.get('modifyTime')  # 修改时间
        self.sysModifyTime = kwargs.get('sysModifyTime')  # 系统修改时间
        self.isdeal = kwargs.get('isdeal') or 0  # 是否处理过，0未处理，1已处理, -n 代表第n次处理失败
        self.id = kwargs.get('id') or 0

    @classmethod
    def do_sync(cls, client: MSsqlClient, objs: list[BaseEntity]):
        if MyTime.timestamp() - int(MyTime.timestampfrom(cls.update_cache_time)) > 24 * 60 * 60:
            cls.update_cache_time = MyTime.timestr()
            init_area_cache()

        # type = 10
        result_num = [0, 0]
        for obj in objs:
            parent_code = obj.parentExtKey
            get_area_cache(parent_code)
            # group_name = obj.regionCode + '-' + obj.regionName
            group_name = obj.regionName
            result = 0
            if obj.isDeleted == 'True':  # 删除
                result = client.execute(f"delete from acscon_group where type = 10 and [desc] = '{obj.regionExtKey}'")
                if result == 0:
                    # 删除失败，不存在该区域
                    result = 1
                    Mylogger.info(f"删除区域 {obj.regionExtKey} 失败，不存在该区域")
                result_num[1] += result

            else:  # 新增或更新
                if area_cache[parent_code] == {}:
                    Mylogger.info(f"新增区域 {obj.regionExtKey} 失败，不存在父区域 {parent_code}")
                    # continue
                else:
                    result = client.execute(
                        f"update acscon_group set name = '{group_name}',pid = '{area_cache[parent_code]['id']}',level= {area_cache[parent_code]['level'] + 1} where type = 10 and [desc] = '{obj.regionExtKey}'"
                    )
                    if result == 0:
                        # 更新失败，不存在该区域
                        result = client.execute(
                            f"insert into acscon_group(name,pid,type,[desc],level) values('{group_name}','{area_cache[parent_code]['id']}',10,'{obj.regionExtKey}',{area_cache[parent_code]['level'] + 1})"
                        )
                    result_num[0] += result

            if result is not None:
                # 同步成功，key = 1 ,否则isdeal 减一
                key = 1 if result == 1 else (int(obj.isdeal) - 1)
                if not cls.write_back_dict.__contains__(str(key)):
                    cls.write_back_dict[str(key)] = []

                cls.write_back_dict[str(key)].append(str(obj.id))

        Mylogger.info(f"area同步成功，写入：{result_num[0]}，删除：{result_num[1]}")
        return super().do_sync(client, objs)


area_cache = {"-1": {'id': 'C9AB162E-4712-E411-976E-7427EA38CA2A', 'level': 0}}


def get_area_cache(code: str):
    if not area_cache.__contains__(code):
        area_cache[code] = {}
        client = MSsqlClient(charset='cp936', **Config.module_config.huada.client_link)
        result = client.select_to_dict(f"select id,level from acscon_group where type = 10 and [desc] = '{code}'")
        if result and len(result) > 0:
            area_cache[code] = result[0]


def init_area_cache():
    client = MSsqlClient(charset='cp936', **Config.module_config.huada.client_link)
    result = client.select_to_dict(f"select id,level,[desc] from acscon_group where type = 10")
    if result and len(result) > 0:
        area_cache.clear()
        area_cache["-1"] = {'id': 'C9AB162E-4712-E411-976E-7427EA38CA2A', 'level': 0}
        for item in result:
            area_cache[item['desc']] = item

    Mylogger.info(f"区域缓存加载成功，共 {len(result)} 条数据")


# init_area_cache()
